<template>
  <div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="商品名字" prop="goodsName">
        <el-input v-model="ruleForm.goodsName" style="width: 50%"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="region">
        <el-select v-model="ruleForm.labelId" placeholder="请选择分类">
          <el-option
            v-for="item in labelData"
            :label="item.labelName"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务">
        <el-col :span="3">
          <el-form-item label="跨市配送">
            <el-switch v-model="ruleForm.isCcd"></el-switch> </el-form-item
        ></el-col>
        <el-col :span="3">
          <el-form-item label="隔日送达">
            <el-switch v-model="ruleForm.isDaysend"></el-switch> </el-form-item
        ></el-col>
        <el-col :span="3">
          <el-form-item label="定期送达">
            <el-switch v-model="ruleForm.isAfp"></el-switch> </el-form-item
        ></el-col>
      </el-form-item>
      <el-form-item label="商品属性">
        <el-col :span="6"
          ><el-form-item label="库存" prop="inventory">
            <el-input
              v-model="ruleForm.inventory"
              style="width: 100%"
              placeholder="请输入数字"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="6">
          <el-form-item label="商品价格(元)" prop="price">
            <el-input
              v-model="ruleForm.price"
              placeholder="请输入数字,最多两位小数"
              style="width: 100%"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="6">
          <el-form-item label="建议零售价(元)" prop="retailPrice">
            <el-input
              v-model="ruleForm.retailPrice"
              style="width: 130%"
              placeholder="请输入数字,最多两位小数"
            ></el-input> </el-form-item
        ></el-col>
        <el-col :span="6"
          ><el-form-item label="计量单位">
            <el-select v-model="ruleForm.unitId" placeholder="请选择分类">
              <el-option
                v-for="item in unitData"
                :label="item.unitName"
                :value="item.id"
                :key="item.id"
              ></el-option>
            </el-select> </el-form-item
        ></el-col>
      </el-form-item>
      <el-form-item label="商品图片">
        <UploadImg @submitImg="setImgs" ref="imgClear" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >立即发布</el-button
        >
      </el-form-item>
      <el-form-item label="商品细节">
        <Article @submitArticle="setArticle" ref="articleClear" />
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import UploadImg from "@/components/UploadImg";
import Article from "@/components/Article";
import { getLableList, getUnitList, saveGoods } from "@/api/productApi";
export default {
  components: { UploadImg, Article },
  data() {
    return {
      ruleForm: {
        goodsName: "",
        labelId: 1,
        mDate: null,
        qDate: null,
        isCcd: false,
        type: [],
        resource: "",
        desc: "",
        unitId: 1,
        price: null,
        isDaysend: true,
        isAfp: true,
        inventory: "",
        retailPrice: "",
      },
      rules: {
        goodsName: [
          { required: true, message: "请输入商品名", trigger: "blur" },
          {
            min: 1,
            max: 80,
            message: "长度在 1 到 80 个字符",
            trigger: "blur",
          },
        ],
        price: [
          {
            required: true,
            message: "请输入价格",
            trigger: "blur",
          },
          {
            required: true,
            message: "请输入数字,最多两位小数",
            trigger: "blur",
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                var regex = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if (!regex.test(value)) {
                  reject("请输入数字,最多两位小数"); // reject with error message
                } else {
                  resolve();
                }
              });
            },
          },
        ],
        retailPrice: [
          {
            required: true,
            message: "请输入价格",
            trigger: "blur",
          },
          {
            required: true,
            message: "请输入数字,最多两位小数",
            trigger: "blur",
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                var regex = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                if (!regex.test(value)) {
                  reject("请输入数字,最多两位小数"); // reject with error message
                } else {
                  resolve();
                }
              });
            },
          },
        ],
        inventory: [
          {
            required: true,
            message: "请输入库存",
            trigger: "blur",
          },
          {
            required: true,
            message: "请输入正整数",
            trigger: "blur",
            validator: (rule, value) => {
              return new Promise((resolve, reject) => {
                var regex = /(^[1-9]\d*$)/;
                if (!regex.test(value)) {
                  reject("请输入数字,最多两位小数"); // reject with error message
                } else {
                  resolve();
                }
              });
            },
          },
        ],
      },
      labelData: [],
      unitData: [],
      detailed: "",
      tempPicture: [],
      initData: null,
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.tempPicture.length == 0) {
            this.$message.info("至少需要上传一张照片");
          } else {
            let tip =
              this.detailed == ""
                ? "当前没有商品的详细介绍，是否确定发布该商品"
                : "是否确定发布该商品";
            this.$confirm(tip, "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                const goodsData = {
                  goodsName: this.ruleForm.goodsName,
                  price: this.ruleForm.price,
                  unitId: this.ruleForm.unitId,
                  detailed: this.detailed,
                  isCcd: this.ruleForm.isCcd ? 1 : 0,
                  isAfp: this.ruleForm.isAfp ? 1 : 0,
                  isDaysend: this.ruleForm.isDaysend ? 1 : 0,
                  labelId: this.ruleForm.labelId,
                  picture: JSON.stringify(this.tempPicture),
                  inventory: this.ruleForm.inventory,
                  retailPrice: this.ruleForm.retailPrice,
                };
                goodsData.mDate = this.ruleForm.mDate;
                goodsData.qDate = this.ruleForm.qDate;
                goodsData.receiveQDate = this.ruleForm.qDate;
                goodsData.receiveMDate = this.ruleForm.mDate;
                //console.log(goodsData)
                saveGoods(goodsData).then((res) => {
                  if (res.code == 0) {
                    this.ruleForm = { ...this.initData };
                    this.$refs.imgClear.clearImg();
                    this.$refs.articleClear.clearHtml();
                    this.$message.success("发布成功");
                  } else {
                    this.$message.error(res.message);
                  }
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消发布",
                });
              });
          }
        } else {
          this.$message.info("请检查数据");
          return false;
        }
      });
    },
    setImgs(fileList) {
      this.tempPicture = fileList;
    },
    setArticle(html) {
      this.detailed = html;
    },
  },
  created() {
    // let a = this.$route.params.name;
    this.initData = { ...this.ruleForm };
    getLableList()
      .then((res) => {
        if (res.code == 0) {
          this.labelData = res.data;
        } else {
          this.$message.warn("获取分类失败" + res.message);
        }
      })
      .catch((err) => {
        this.$message.warn("获取分类失败");
      });
    getUnitList()
      .then((res) => {
        if (res.code == 0) {
          this.unitData = res.data;
        } else {
          this.$message.warn("获取单位失败" + res.message);
        }
      })
      .catch((err) => {
        this.$message.warn("获取单位失败");
      });
  },
};
</script>